package org.itboys.manager;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.itboys.fuzion.constant.FuzionConstants;
import org.itboys.fuzion.dto.FuzionMemberRedisDto;
import org.itboys.fuzion.entity.FuzionMember;
import org.itboys.fuzion.entity.ScoreLevel;
import org.itboys.fuzion.mysql.orm.FuziongMemberStatistics;
import org.itboys.fuzion.mysql.service.FuziongMemberStatisticsService;
import org.itboys.fuzion.service.FuzionMemberService;
import org.itboys.fuzion.service.ScoreLevelService;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.seller.entity.Seller;
import org.itboys.seller.service.SellerService;
import org.itboys.tools.WeixinSendInfoThread;
import org.itboys.weixin.entity.WeixinConfig;
import org.itboys.weixin.entity.WeixinSendInfo;
import org.itboys.weixin.service.WeixinConfigService;
import org.itboys.weixin.service.WeixinSendInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;

/**
 * 会员和店铺之间的关系
 * @author weisky
 *
 * 2016年4月12日
 */
@Service
public class SellerMemberService {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private SellerService sellerService;
	@Autowired
	private FuzionMemberService fuzionMemberService;
	@Autowired
	private FuziongMemberStatisticsService fuziongMemberStatisticsService;
	@Autowired
	private WeixinSendInfoService weixinSendInfoService;
	@Autowired
	private WeixinConfigService weixinConfigService;
	@Autowired
	private ScoreLevelService scoreLevelService;
	
	/**
	 * 创建一个店铺的同时，为他生成一个会员；这个会员代表着这个店铺  方便后面的佣金计算
	 * @param seller
	 * @param logos
	 * @param mainImgs
	 * @return
	 */
	public boolean addSellerAndCreateMember(Seller seller, MultipartFile logos, MultipartFile mainImgs){
		long tempSellerId = 0l;
		try{
			tempSellerId = seller.getId();
			boolean resu = sellerService.insert(seller, logos, mainImgs);
			if(!resu){//对店铺的操作失败
				return false;
			}
			
			if(tempSellerId == 0){//新增一个店铺
				//先判断数据库中是否已经存在这个会员  若没有这个会员  再添加
				//一个微信账号只能生成一个会员类型是99的店铺会员
				Map<String, Object> sellerMember = Maps.newHashMapWithExpectedSize(2);
				sellerMember.put("weixinId", seller.getWeixinId());
				sellerMember.put("type", FuzionConstants.Seller.SELLER_SELF_MEMBER);
				List<FuzionMember> fm = fuzionMemberService.list(sellerMember);
				if(fm.isEmpty()){
					FuzionMember fmember = new FuzionMember();
					fmember.setLogo(seller.getLogo());
					fmember.setNickname(seller.getName());
					fmember.setUsername(seller.getName());
					fmember.setRecLevel(FuzionConstants.TYPE_ZERO);
					fmember.setSellerId(seller.getId());
					fmember.setType(FuzionConstants.Seller.SELLER_SELF_MEMBER);
					fmember.setWeixinId(seller.getWeixinId() != null?seller.getWeixinId().toString() : "");
					fuzionMemberService.save(fmember);
					fmember.setPath(FuzionConstants.Seller.SELLER_MEMBER_PATH + fmember.getId() + FuzionConstants.Seller.SELLER_MEMBER_PATH );
					fmember.setRecId(fmember.getId());//推荐人是他自己
					fuzionMemberService.update(fmember);
					logger.info("创建店铺自己的会员成功：FuzionMember=" + JSON.toJSONString(fmember));
					
				}
			}
			return true;
		}catch(Exception e){
			e.printStackTrace();
			if(tempSellerId == 0){
				sellerService.dele(seller.getId());//如果创建店铺自己的会员失败，就把刚刚新增的店铺信息删除
			}
			logger.error("SellerMemberService.addSellerAndCreateMember err");
		}
		return false;
	}
	
	/**
	 * 带有分页组装会员信息
	 * @param param
	 * @param request
	 * @return
	 */
	public Page<FuzionMember> listByPage(Map<String, Object> param, HttpServletRequest request){
		Page<FuzionMember> page = fuzionMemberService.pageQuery(param, request);
		if(page != null && page.getData() != null){
			page.getData().forEach(pg -> {
				if(pg.getRecId() != null){//设置推荐人的名字
					FuzionMember fm = fuzionMemberService.getById(pg.getRecId());
					if(fm != null){
						String name = (StringUtils.isBlank(fm.getNickname()) ? fm.getUsername() : fm.getNickname());
						pg.setRecName(name);
					}
				}
				if(pg.getSellerId() != null){//设置会员所属的店铺名字
					Seller ss = sellerService.getById(pg.getSellerId());
					if(ss != null){
						pg.setSellerName(ss.getName());
					}
				}
			});
		}
		return page;
	}
	
	public static void main(String[] args) {
		String cc = "qwe{a}";
		System.out.println(cc.replace("{as}", "xxxx"));
	}
	
	/**
	 * 扫描二维码时，新增或者修改大乱斗的会员信息
	 * @param member
	 */
	public void saveFuzionMember(FuzionMember member){
		FuzionMember fmm = fuzionMemberService.getByField("openId", member.getOpenId());
		if(fmm != null){//如果是之前关注过的  暂时不做任何操作
			return ;
		}
		String recName = null;
		String recOpenId = null;
		
		if(member.getRecId() != null){//有推荐人
			FuzionMember recMember = fuzionMemberService.getById(member.getRecId());
			if(recMember != null){//推荐人还存在
				recName = recMember.getNickname();
				recOpenId = recMember.getOpenId();
				
				member.setLevel(recMember.getLevel() + 1);
				member.setRecLevel(recMember.getLevel() + 1);
				member.setSellerId(recMember.getSellerId());//设置店铺ID
				member.setRecId(recMember.getId());
				fuzionMemberService.save(member);
				member.setPath(recMember.getPath() + member.getId() + FuzionConstants.Seller.SELLER_MEMBER_PATH);
				fuzionMemberService.update(member);
				logger.info("创建会员成功(有推荐人)：FuzionMember="+JSON.toJSONString(member));
				
				//根据推荐的人数  设置会员等级
				FuziongMemberStatistics fms = fuziongMemberStatisticsService.getByMember(member.getRecId());
				fms.setMemberId(member.getRecId());
				Long recCount = fuzionMemberService.countMemberByRecId2(member.getRecId());//已经推荐的会员数量
				//int beanNum = fms.getEnergyBean();//获取历史购买的能量豆数量 能量豆的数量要比已经推荐的会员数量多一个
				
				ScoreLevel score1 = scoreLevelService.getById(1L);//会员等级青铜
				ScoreLevel score2 = scoreLevelService.getById(2L);//会员等级白金
				ScoreLevel score3 = scoreLevelService.getById(3L);//会员等级王者
				ScoreLevel score4 = scoreLevelService.getById(4L);//会员等级战神
				ScoreLevel score5 = scoreLevelService.getById(5L);//会员等级天罡
				ScoreLevel score6 = scoreLevelService.getById(6L);//会员等级教父
				/*ScoreLevel score7 = scoreLevelService.getById(7L);//会员等级待定
				ScoreLevel score8 = scoreLevelService.getById(8L);//会员等级待定
				ScoreLevel score9 = scoreLevelService.getById(9L);//会员等级待定
				ScoreLevel score10 = scoreLevelService.getById(10L);//会员等级待定
*/				
				
				//根据推荐人判断  这里的会员等级ID都是写死了
				String scoreName = null;
				if(recCount > score1.getStartScore() && recCount < score1.getEndScore()){//推荐人  0<n<3 青铜
					if(fms.getScoreId() < 1L){
						fms.setScoreId(1L);
						scoreName = score1.getLevelName();
					}
				}else if(score2.getStartScore() <= recCount && recCount < score2.getEndScore()){  //3<=n<9 白金
					if(fms.getScoreId()<2L){
						fms.setScoreId(2L);
						scoreName = score2.getLevelName();
					}
				}else if(recCount >= score3.getStartScore() && recCount < score3.getEndScore()){//  9<=n<60 王者
					if(fms.getScoreId()<3L){
						fms.setScoreId(3L);
						scoreName = score3.getLevelName();
					}
				}else if(recCount >= score4.getStartScore() && recCount < score4.getEndScore()){//  60<=n<600 战神
					if(fms.getScoreId()<4L){
						fms.setScoreId(4L);
						scoreName = score4.getLevelName();
					}
				}else if(recCount >= score5.getStartScore() && recCount < score5.getEndScore()){//  600<=n<2000 天罡
					if(fms.getScoreId()<5L){
						fms.setScoreId(5L);
						scoreName = score5.getLevelName();
					}
				}else if(recCount >= score6.getStartScore() && recCount < score6.getEndScore()){//  2000<=n<999999 教父
					if(fms.getScoreId()<6L){
						fms.setScoreId(6L);
						scoreName = score6.getLevelName();
					}
				}
				
				//已结不需要判断能量豆了   会员在购买能量豆的时候   会去判断能量豆的数据是否满足条件了   所以下面不需要再判断了
				//根据能量豆判断  
				/*if(beanNum > score1.getStartScore() && beanNum <= score1.getEndScore()){//青铜  0<n<=3
					if(fms.getScoreId() < 1L){
						fms.setScoreId(1L);
						scoreName = score1.getLevelName();
					}
				}else if(4 <= beanNum && beanNum <= 9){//白金   3<n<=9
					if(fms.getScoreId() < 2L){
						fms.setScoreId(2L);
						scoreName = "白金";
					}
				}else if(beanNum >=10){//王者  9<n<=60
					if(fms.getScoreId() < 3L){
						fms.setScoreId(3L);
						scoreName = "王者";
					}
				}*/
				
				//告知会员等级提升了
				if(StringUtils.isNotBlank(scoreName)){
					
					fuziongMemberStatisticsService.updateByMemberId(fms);//如果等级的名称为空  可以认为会员等级没有变化  也就不需要update了
					
					FuzionMemberRedisDto redis_fuzion_member = fuzionMemberService.getFuzionMemberRedisDto(member.getRecId());
					WeixinSendInfo wsss = weixinSendInfoService.getByKey("score_level_to_up");
					String messagess = wsss.getValue().replace("{scoreName}", scoreName);
					WeixinSendInfoThread.sendMessage(redis_fuzion_member.getAppId(), redis_fuzion_member.getAppSecret(), 
							redis_fuzion_member.getOpenId(), messagess);
				}
			}else{//如果推荐人不存在  推送信息告知   推荐人失效  将推荐人暂时设置为店铺的会员
				Map<String, Object> sellerMember = Maps.newHashMapWithExpectedSize(2);
				sellerMember.put("weixinId", member.getWeixinId());
				sellerMember.put("type", FuzionConstants.Seller.SELLER_SELF_MEMBER);
				List<FuzionMember> fm = fuzionMemberService.list(sellerMember);
				if(!fm.isEmpty()){
					FuzionMember fmember = fm.get(0);//取店铺自己的会员ID
					member.setLevel(fmember.getLevel() + 1);
					member.setRecLevel(fmember.getLevel() + 1);
					member.setSellerId(fmember.getSellerId());//设置店铺ID
					member.setRecId(fmember.getId());//把推荐人设置成店铺自己
					fuzionMemberService.save(member);
					member.setPath(fmember.getPath() + member.getId() + FuzionConstants.Seller.SELLER_MEMBER_PATH);
					fuzionMemberService.update(member);
					logger.info("创建会员成功(推荐人失效，将推荐人暂时设置为店铺的会员)：FuzionMember="+JSON.toJSONString(member));
					
					recName = fmember.getNickname();
				}
			}
		}else{//没有推荐人   将推荐人暂时设置为店铺的会员
			Map<String, Object> sellerMember = Maps.newHashMapWithExpectedSize(2);
			sellerMember.put("weixinId", member.getWeixinId());
			sellerMember.put("type", FuzionConstants.Seller.SELLER_SELF_MEMBER);
			List<FuzionMember> fm = fuzionMemberService.list(sellerMember);
			if(!fm.isEmpty()){
				FuzionMember fmember = fm.get(0);//取店铺自己的会员ID
				member.setLevel(fmember.getLevel() + 1);
				member.setRecLevel(fmember.getLevel() + 1);
				member.setSellerId(fmember.getSellerId());//设置店铺ID
				member.setRecId(fmember.getId());//把推荐人设置成店铺自己
				fuzionMemberService.save(member);
				member.setPath(fmember.getPath() + member.getId() + FuzionConstants.Seller.SELLER_MEMBER_PATH);
				fuzionMemberService.update(member);
				logger.info("创建会员成功(没有推荐人，将推荐人暂时设置为店铺的会员)：FuzionMember="+JSON.toJSONString(member));
				
				recName = fmember.getNickname();
			}
		}
		
		//初始化会员的收益信息
		FuziongMemberStatistics fms = new FuziongMemberStatistics();
		fms.setMemberId(member.getId());
		fms.setScoreId(0L);
		fms.setTotalMoney(0);
		fms.setWithdrawTotalMoney(0);
		fms.setNowTotalMoney(0);
		fms.setEnergyBean(0);
		fms.setBuyCount(0);
		fms.setNowEnergyBean(0);
		fms.setDynamicIncome(0);
		fms.setStaticIncome(0);
		fms.setSellerId(member.getSellerId());
		fms.setPlayNum(0);
		fuziongMemberStatisticsService.insert(fms);
		
		WeixinConfig weixinConfig = weixinConfigService.getById(Long.parseLong(member.getWeixinId()));
		if(weixinConfig != null){
			//推送信息
			WeixinSendInfo ws = weixinSendInfoService.getByKey("first_follow_success");
			String message = ws.getValue().replace("{recName}", recName);//推送给关注人的内容
			WeixinSendInfoThread.sendMessage(weixinConfig.getAppId(), weixinConfig.getAppSecret(), member.getOpenId(), message);
			
			if(StringUtils.isNotBlank(recOpenId)){
				WeixinSendInfo recws = weixinSendInfoService.getByKey("myteam_add_member");
				String recmessage = recws.getValue().replace("{memberName}", member.getNickname());//推送给推荐人的内容
				WeixinSendInfoThread.sendMessage(weixinConfig.getAppId(), weixinConfig.getAppSecret(), recOpenId, recmessage);
			}
			
		}
		
	}
	
}
